
<template>
  <div class="lessionItem">
    名称:{{Person.name}}<br />
    年龄:{{Person.age}}<br />
    工作:工作地址是 {{Person.work.name}} 工资是 {{Person.work.salary}}<br />
    <button @click="changeName">修改名字</button><br />
    <button @click="changeAge">修改年龄</button><br />
    <button @click="changePerson">修改整个人</button><br />
    <button @click="changeWorkType">修改工作类型</button><br />
    <button @click="changeSalary">修改工作月薪</button><br />
    <button @click="changeWork">修改工作</button><br />
  </div>
  <div class="lessionItem watchEffect">
    <p>当前水温:{{temp}} 度</p>
    <p>当前水位:{{height}} M</p>
    <button @click="changeTemp">改变水温</button>
    <button @click="changeHeight">改变水位</button>
  </div>
  <div class="lessionItem">
    <h2 ref="refh2">我是 ref 控制的</h2>
    <button @click="showRef">查看 ref</button>
  </div>
</template>
  <script setup  lang="ts">
import {
  ref,
  defineProps,
  defineEmits,
  reactive,
  toRef,
  toRefs,
  computed,
  watch,
  watchEffect,
} from "vue";
// 监听的方法
let Person = reactive({
  name: "张三",
  age: 18,
  work: {
    name: "前端开发",
    salary: 10000,
    home: {
      address: "北京",
      name: "北京",
    },
  },
});
let Person2 = ref({
  name: "赵六",
  age: 100,
});
function changeName() {
  Person.name = "李四";
}
function changeAge() {
  Person.age = 20;
}
function changePerson() {
  // 这么写 无法修改 Person 对象 因为 通过字面量的形式 直接修改 是在内存中生成了一块新的地址 给 person 重新赋值了 但不是响应式的数据
  // Person = {
  //   name: "王五",
  //   age: 22,
  // };
  // // Person 其实变成 王五了 但是 不是响应式的数据 所以的组件都不会更新
  // console.log(Person, "Person");
  // Object.assign(Person, {
  //   name: "王五",
  //   age: 22,
  // });
}
function changeWorkType() {
  Person.work.name = "后端开发";
}
function changeSalary() {
  Person.work.salary = 20000;
}
function changeWork() {
  Person.work = {
    home: {
      address: "上海",
      name: "上海",
    },
    name: "产品经理",
    salary: 30000,
  };
  console.log(Person, "Person");
}
//
// watch(
//   [() => Person.work.name, () => Person.work.home.address],
//   (newVal, oldVal) => {
//     console.log(newVal, oldVal);
//   }
// );

/* --------------------watchEffect---------- */
let temp = ref(0);
let height = ref(0);
function changeTemp() {
  temp.value += 10;
}
function changeHeight() {
  height.value += 10;
}
watch([temp, height], (newVal, oldVal) => {
  console.log(newVal, oldVal);
  if (temp.value > 60 || height.value > 80) {
    console.log("温度过高或者水位过高", newVal, oldVal);
  }
});
// 用 watchEffect 监听 temp 和 height 的变化
watchEffect(() => {
  if (temp.value > 60 || height.value > 80) {
    console.log("温度过高或者水位过高");
  }
});
// ref
let refh2 = ref();
function showRef() {
  console.log(refh2.value);
}
</script>
  <style lang="scss" scoped>
.lessionItem {
  width: 100%;
  height: 100%;
  background: skyblue;
  margin-top: 20px;
  .lessionItem > div,
  button,
  h3,
  p {
    margin-bottom: 20px;
  }
}
</style>